#include <QDebug>
#include <QRegExp>
#include <QProcess>
#include <QUrl>

#include "WindowsPing.h"

WindowsPing::WindowsPing(QObject *parent) :
    PingInterface(parent),
    mPingProcess( new QProcess(this) )
{
    connect( mPingProcess, SIGNAL(finished(int)), this, SLOT(processFinished(int)) );
}

void WindowsPing::send( const QUrl &url )
{
    qDebug() << "WindowsPing: Sending ping to " + url.toString();

    QString exec = "ping";
    QStringList params;
    params << url.host();

    qDebug() << "WindowsPing: " + exec + " " + params.join(" ");

    mPingProcess->start( exec, params );
}

void WindowsPing::processFinished( int exitCode )
{
    qDebug() << QString( "WindowsPing: exitCode = %1" ).arg( exitCode );

    QString result = mPingProcess->readAll();
    mPingProcess->close();

    qDebug() << result;

    /* Check if host was unavailable. "100%" occurs only if all packets where lost.
       Also check if exitCode was not 0. In this case the url is probably wrong. */
    if ( exitCode == 0 && !result.contains("100%") )
    {
        /* Read average time. The regular expressions searches the last number with
           suffix ms. That's the average time. */
        QRegExp rx( ".+= (\\d+)ms\\s+$" );
        if ( rx.indexIn(result) != -1 )
        {
            int averageTime = rx.cap(1).toInt();
            qDebug() << QString( "WindowsPing: Average time = %1ms" ).arg( averageTime );

            emit pingResult( averageTime );
        }
        else
        {
            qFatal( "WindowsPing: Regular expression has no result." );
        }
    }
    else
    {
        qDebug() << "WindowsPing: Host unavailable.";

        emit hostUnavailable();
    }
}
